<template>
  <el-card class="box-card">
    <div slot="header">
      <span>{{ dict.id ? this.$t('common.edit') : this.$t('common.add') }}</span>
    </div>
    <el-form ref="form" :model="dict" :rules="rules" label-position="right" label-width="100px">
      <el-form-item label="字典名称" prop="dictName">
        <el-input v-model="dict.dictName" />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input v-model="dict.dictType" />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input v-model="dict.remark" />
      </el-form-item>
    </el-form>
    <div class="edit-footer">
      <el-button type="primary" plain :loading="buttonLoading" @click="submitForm">
        {{ $t('common.confirm') }}
      </el-button>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'DictEdit',
  data() {
    return {
      dict: this.initDict(),
      buttonLoading: false,
      rules: {
        dictName: [
          { required: true, message: this.$t('rules.require'), trigger: 'blur' }
        ],
        dictType: [
          { required: true, message: this.$t('rules.require'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    initDict() {
      return {
        dictName: '',
        dictType: '',
        remark: ''
      }
    },
    setDict(val) {
      this.reset()
      this.dict = {
        id: val.id || '',
        dictName: val.dictName || '',
        dictType: val.dictType || '',
        remark: val.remark || ''
      }
    },
    reset() {
      // 先清除校验，再清除表单，不然有奇怪的bug
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      this.dict = this.initDict()
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (!this.dict.id) {
            // create
            this.$post('/system/dict', this.dict).then(() => {
              this.$message({
                message: this.$t('tips.createSuccess'),
                type: 'success'
              })
              this.$emit('success')
              this.reset()
              this.buttonLoading = false
            }).catch(() => {
              this.buttonLoading = false
            })
          } else {
            // update
            this.$put('/system/dict', this.dict).then(() => {
              this.$message({
                message: this.$t('tips.updateSuccess'),
                type: 'success'
              })
              this.$emit('success')
              this.reset()
              this.buttonLoading = false
            }).catch(() => {
              this.buttonLoading = false
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .edit-footer{
    text-align: right;
  }
  .box-card{
    border-radius: 0;
    border: none;
    &.is-always-shadow{
      box-shadow: none;
    }
  }
</style>
